import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { SearchSelect } from 'scd'
import { Skeleton, Spin, Modal, Form, Row, Col, Table, Card, Button, Input, Tree, Select } from 'antd'
import SearchForm from './SearchForm'
import { authType, resBizIds } from '../mapping'
import "./index.less"
const FormItem = Form.Item;
const Option = Select.Option
const { TreeNode } = Tree;
const confirm = Modal.confirm;


@connect(({ loading, dispatch, app, role }) => ({
  app,
  role,
  reloading: loading.effects['role/getRoleList'],
  treeloading: loading.effects['role/getResourcesTree'],
  addloading: loading.effects['role/addRole'],
  infoloading: loading.effects['role/getRoleInfoById'],
  editloading: loading.effects['role/editRole'],
}))
@Form.create()
class RoleIndex extends PureComponent {
  state = {
    visiable: false,
    sortedInfo: null,
    pageSizeOptions: ['10', '20', '50', '100', '200'],
    pageNum: 1,
    pageSize: 10,
    resourcesIdList: [],
    resBizList: "",
    modalType: ""
  }

  returnList = (list) => {
    let arr = []
    if (list.length > 0) {
      list.forEach(item => {
        if (item.indexOf("best") === -1) {
          arr.push(item)
        }
      })
    }
    return arr
  }

  onShowSizeChange = (pageNum, pageSize) => {  //当几条一页的值改变后调用函数
    const { dispatch, app: { singleOriginal } } = this.props
    dispatch({
      type: 'role/getRoleList',
      payload: {
        pageNum,
        pageSize,
        orgId: singleOriginal.id,
      }
    })
    this.setState({
      pageNum,
      pageSize
    })

  }
  onChange = (pageNum) => {
    const { pageSize } = this.state
    const { dispatch, app: { singleOriginal } } = this.props
    dispatch({
      type: 'role/getRoleList',
      payload: {
        pageNum,
        orgId: singleOriginal.id,
        pageSize: pageSize
      }
    })
    this.setState({ pageNum })
  }

  showModal = (type, data) => {
    const { dispatch, app: { singleOriginal } } = this.props
    this.setState({
      visiable: true,
      modalType: type,
      currentData: data,
    })
    if (type === "edit") {
      new Promise((resolve) => {
        dispatch({
          type: 'role/getRoleInfoById',
          payload: {
            resolve,
            id: data.id
          }
        })
      }).then((response) => {
        if (response.code === 1 && response.data) {
          let resourcesList = response.data.resourcesList
          if (resourcesList) {
            let checkList = resourcesList.map(item => {
              return item.id
            })
            this.setState({
              resourcesIdList: checkList
            })
          }
        }
      })
    } else {
      dispatch({
        type: 'role/getResourcesTree',
        payload: {
          authType: 0,
          orgId: singleOriginal.id,
        }
      })
      this.setState({
        resourcesIdList: []
      })
    }
  }

  handleOk = (e) => {
    e.preventDefault();
    const { pageNum, pageSize, resourcesIdList, resBizList, modalType, currentData } = this.state
    const { dispatch, form: { validateFieldsAndScroll, resetFields }, app: { singleOriginal } } = this.props
    validateFieldsAndScroll((error, value) => {
      if (!value || error) return
      const dispatchType = this.switchType(modalType)
      new Promise((resolve) => {
        dispatch({
          type: dispatchType.url,
          payload: {
            resolve,
            ...value,
            resourcesIdList: this.returnList(resourcesIdList),
            resBizIdList: resBizList,
            id: modalType === 'edit' ? currentData.id : null,
            orgId: singleOriginal.id,
            status: 1
          }
        })
      }).then((code) => {
        if (code === 1) {
          resetFields()
          this.setState({
            visiable: false,
            resourcesIdList: [],
          })
          dispatch({
            type: 'role/getRoleList',
            payload: {
              pageNum,
              pageSize,
              orgId: singleOriginal.id
            }
          })
        }
      })
    })
  }
  handleCancel = () => {
    const { form: { resetFields } } = this.props
    this.setState({
      visiable: false,
    })
    resetFields()
  }
  showDeleteConfirm = (data) => {//删除弹窗 部门or人员
    const { pageNum, pageSize } = this.state
    const { dispatch, app: { singleOriginal } } = this.props
    confirm({
      title: '确定要删除吗?',
      content: '删除组织后改组织下的公司和部门、人员会xxx，你还要删除吗？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取 消',
      onOk() {
        new Promise((resolve) => {
          dispatch({
            type: 'role/deleteRole',
            payload: {
              resolve,
              id: data.id,
              orgId: singleOriginal.id,
            }
          })
        }).then((code) => {
          if (code === 1) {
            dispatch({
              type: 'role/getRoleList',
              payload: {
                pageNum,
                pageSize,
                orgId: singleOriginal.id
              }
            })
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  switchType(type) {
    switch (type) {
      case "create":
        return { url: "role/addRole", type: "create" }
        break;
      case "edit":
        return { url: "role/editRole", type: "edit" }
        break;
    }
  }

  onTreeCheck = (checkedKeys, info) => {
    let halfCheckedKeys = info.halfCheckedKeys
    if (halfCheckedKeys.length > 0) {
      let resBizList = []
      halfCheckedKeys.forEach(item => {
        if (item.indexOf("best") > -1) {
          resBizList.push(item)
        }
      })
      checkedKeys.forEach(item => {
        let idx = item.indexOf("best")
        if (idx > -1) {
          if (resBizList.indexOf(item) === -1) {
            resBizList.push(item)
          }
        }
      })
      resBizList.forEach(item => {
        item = item.substring(5, item.length)
      })
      resBizList = resBizList.map(item => {
        return item = item.substring(5, item.length)
      })
      this.setState({
        resourcesIdList: checkedKeys,
        resBizList: resBizList,
      })
    } else {
      if (checkedKeys.length === 0) {
        this.setState({
          resourcesIdList: checkedKeys,
          resBizList: []
        })
        return
      }
      let resBizList = []
      checkedKeys.forEach(item => {
        let idx = item.indexOf("best")
        if (idx > -1) {
          if (resBizList.indexOf(item) === -1) {
            resBizList.push(item)
          }
        }
      })
      resBizList = resBizList.map(item => {
        return item = item.substring(5, item.length)
      })
      this.setState({
        resourcesIdList: checkedKeys,
        resBizList: resBizList
      })
    }
  }

  sorter = (pagination, filters, sorter) => {
    const { pageNum, pageSize } = this.state
    const { dispatch, app: { singleOriginal } } = this.props
    if (sorter && sorter.order && sorter.columnKey) {

      let disType = { url: "role/getRoleList", orderBy: sorter.columnKey }
      switch (sorter.columnKey) {
        case "authType":
          disType.desc = sorter.order === "ascend" ? false : true
          break;
        case "resBizIds":
          disType.desc = sorter.order === "ascend" ? false : true
          break;
      }
      dispatch({
        type: disType.url,
        payload: {
          pageNum,
          pageSize,
          ...disType,
          orgId: singleOriginal.id
        }
      })
      // console.log(`order:${sorter.order}--columnKey:${sorter.columnKey}---->`, sorter)
    }
  }

  renderTree = (orgTree) => {//组织树渲染
    return orgTree.map((item) => {
      if (!item.name) return
      const orgName = item.name
      if (item.children && item.children.length !== 0) {
        return (
          <TreeNode key={item.id} title={orgName}>
            {this.renderTree(item.children)}
          </TreeNode>
        )
      }
      return <TreeNode key={item.id} title={orgName} />
    })
  }

  selectChange = (key) => {
    const { dispatch, app: { singleOriginal } } = this.props
    dispatch({
      type: 'role/getResourcesTree',
      payload: {
        orgId: singleOriginal.id,
        authType: key
      }
    })
  }
  // const { messageList } = app
  render() {
    const { visiable, sortedInfo, pageSizeOptions, pageNum, pageSize, modalType, currentData, resourcesIdList } = this.state
    const { reloading, treeloading, addloading, infoloading, editloading,
      form: { getFieldDecorator }, role: { roleObj, singleRoleInfo, resourcesTree, resourcesTreeMap } } = this.props
    const columns = [
      {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
      }, {
        title: '产品线',
        dataIndex: '',
        key: 'resBizIdList',
        render: (record) => {
          if (record.resBizIdList.length > 0) {
            return record.resBizIdList.map((item, index) => {
              return <Col key={index}>{index + 1}-{resBizIds[`${item}`]}</Col>
            })
          } else {
            return "暂无产品线"
          }
        },
        sorter: true,
      }, {
        title: '角色类型',
        dataIndex: '',
        key: 'authType',
        render: (record) => {
          return `${authType[`${record.authType}`]}` || "暂无角色类型"
        },
        sorter: true,
      }, {
        title: '操作',
        dataIndex: '',
        key: '',
        width: 150,
        // align: "center",
        render: (record) => {
          return (<Row>
            <Col span={12}><a onClick={e => this.showModal("edit", record)} style={{ marginRight: "10px" }}>编辑</a></Col>
            <Col span={12}><a onClick={e => { this.showDeleteConfirm(record) }} style={{ color: "#f5222d" }}>删除</a></Col>
          </Row>)
        }
      }
    ];
    const searchProps = {
      pageNum,
      pageSize
    }
    return (
      <React.Fragment>
        <Row>
          <SearchForm searchProps={searchProps} />
          <Button type="primary" onClick={e => this.showModal("create")}>创建</Button>
          <Spin
            size="small"
            spinning={!!reloading}
            tip="加载中..." >
            {roleObj && <Table
              rowKey="id"
              style={{ marginTop: '20px' }}
              columns={columns}
              dataSource={roleObj.list}
              onChange={this.sorter}
              pagination={{
                total: roleObj.total, //数据总数量
                pageSizeOptions: pageSizeOptions,  //显示几条一页
                defaultPageSize: pageSize, //默认显示几条一页
                showSizeChanger: true,  //是否显示可以设置几条一页的选项
                showQuickJumper: true,
                onShowSizeChange: this.onShowSizeChange,
                onChange: this.onChange,
                showTotal: (total, range) => `当前(${range[0]}-${range[1]})条 -- 共${total}条记录`
              }}
            />}
          </Spin>

          <Modal
            title={modalType === 'create' ? "创建角色" :
              <span>编辑<span style={{ color: '#067dc6' }}>{currentData && currentData.name || "XXX"}</span>角色信息</span>
            }
            visible={visiable}
            onOk={this.handleOk}
            confirmLoading={modalType === 'create' ? !!addloading : !!editloading}
            onCancel={this.handleCancel}>
            <Spin
              size="small"
              spinning={modalType === "edit" ? !!infoloading : !!treeloading}
              tip="加载中..." >
              <Form layout="vertical">
                <FormItem label="用户姓名">
                  {getFieldDecorator('name', {
                    initialValue: modalType === 'edit' ? singleRoleInfo.name : null,
                    rules: [{ required: true, message: '请输入用户姓名或手机号码', },],
                  })(<Input placeholder="请输入姓名" />)}
                </FormItem>
                <FormItem label="角色类型" >
                  {getFieldDecorator('authType', {
                    initialValue: modalType === 'edit' ? `${singleRoleInfo.authType}` : "0",
                    onChange: this.selectChange
                  })
                    (<Select placeholder="请选择">
                      <Option key="0" value="0">组织类型</Option>
                      <Option key="1" value="1">业务类型</Option>
                    </Select>)}
                </FormItem>
                <FormItem label="角色权限" >
                  <Card>
                    {resourcesTree.length > 0 ? <Tree
                      checkable
                      // expandedKeys={resourcesIdList}
                      // selectedKeys={resourcesTreeMap}
                      checkedKeys={resourcesIdList}
                      onCheck={this.onTreeCheck}
                    >
                      {resourcesTree.map(item => {
                        return (<TreeNode title={item.bizName} key={`best-${item.bizId}`} data-key={item.bizId}>
                          {item.resourcesList && this.renderTree(item.resourcesList)}
                        </TreeNode>)
                      })}
                    </Tree> : "暂无任务权限设置"}
                  </Card>
                </FormItem>
              </Form>
            </Spin>
          </Modal>
        </Row>
      </React.Fragment>
    )
  }
}

export default RoleIndex;
